<template>
  <div class="app-detail-page">
    <!-- 顶部导航栏 -->
    <div class="top-bar">
      <div class="left-section">
        <div class="app-info">
          <div class="app-title-row">
            <h1 class="app-name">{{ getAppDisplayName() }}</h1>
            <a-tag v-if="shouldShowStatusTag()" :color="getStatusColor()" class="app-status-tag">
              <template #icon>
                <component :is="getStatusIcon()" />
              </template>
              {{ getAppStatus() }}
            </a-tag>
          </div>
          <div class="app-meta">
            <span v-if="shouldShowTypeTag()" class="app-type">
              {{ getAppTypeLabel() }}
            </span>
            <span class="create-time">{{ formatTime(appInfo?.createTime) }}</span>
          </div>
        </div>
      </div>
      <div class="right-section">
        <a-space>
          <a-button
            v-if="appInfo?.deployKey || appInfo?.deployUrl"
            @click="openDeployedApp"
            class="view-btn"
          >
            <template #icon>
              <LinkOutlined />
            </template>
            查看部署应用
          </a-button>
          <a-button
            type="primary"
            @click="handleDeploy"
            :loading="isDeploying"
            :disabled="!canDeploy"
            class="deploy-btn"
          >
            <template #icon>
              <CloudUploadOutlined />
            </template>
            {{ appInfo?.deployKey ? '重新部署' : '部署应用' }}
          </a-button>
          <a-dropdown placement="bottomRight">
            <a-button class="more-btn">
              <template #icon>
                <MoreOutlined />
              </template>
            </a-button>
            <template #overlay>
              <a-menu>
                <a-menu-item @click="downloadCode">
                  <template #icon>
                    <DownloadOutlined />
                  </template>
                  下载代码
                </a-menu-item>
                <a-menu-divider />
                <a-menu-item @click="goToMyApps">
                  <template #icon>
                    <ArrowLeftOutlined />
                  </template>
                  返回列表
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </a-space>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧对话区域 -->
      <div class="chat-section" :style="{ width: ${leftWidth}% }">
        <!-- 消息区域 -->
        <div class="messages-container" ref="messagesRef">
          <!-- 加载更多按钮 -->
          <div v-if="hasMoreHistory" class="load-more-wrapper">
            <a-button
              type="text"
              @click="loadMoreHistory"
              :loading="isLoadingHistory"
              class="load-more-btn"
            >
              <template #icon>
                <UpOutlined />
              </template>
              加载更多历史消息
            </a-button>
          </div>

          <!-- 消息列表 -->
          <div class="messages-list">
            <div
              v-for="(message, index) in messages"
              :key="message.id || index"
              class="message-item"
              :class="{
                'user-message': message.messageType === 'user',
                'ai-message': message.messageType === 'assistant',
              }"
            >
              <div class="message-avatar">
                <a-avatar
                  v-if="message.messageType === 'user'"
                  :size="36"
                  class="user-avatar"
                  :src="loginUserStore.loginUser.userAvatar"
                >
                  <template #icon>
                    <UserOutlined />
                  </template>
                </a-avatar>
                <a-avatar v-else :size="36" class="ai-avatar">
                  <template #icon>
                    <AndroidOutlined />
                  </template>
                </a-avatar>
              </div>
              <div class="message-content">
                <div class="message-header">
                  <span class="sender-name">
                    {{
                      message.messageType === 'user'
                        ? loginUserStore.loginUser.userName || '我'
                        : 'AI 助手'
                    }}
                  </span>
                  <span class="message-time">{{ formatMessageTime(message.createTime) }}</span>
                </div>
                <div class="message-text">
                  <!-- AI消息：支持混合文本和代码 -->
                  <div v-if="message.messageType === 'assistant'" class="ai-message-content">
                    <!-- 渲染消息片段 -->
                    <template v-if="message.chunks && message.chunks.length > 0">
                      <div
                        v-for="(chunk, chunkIndex) in message.chunks"
                        :key="chunkIndex"
                        class="message-chunk"
                      >
                        <pre
                          v-if="chunk.type === 'code'"
                          class="code-block"
                        ><code>{{ chunk.content }}</code></pre>
                        <div v-else class="text-chunk" v-html="formatMessage(chunk.content)"></div>
                      </div>
                    </template>
                    <!-- 兼容旧格式 -->
                    <div v-else v-html="formatMessage(message.message)"></div>
                    <span v-if="message.isStreaming" class="cursor">|</span>
                  </div>
                  <!-- 用户消息：纯文本 -->
                  <div v-else>{{ message.message }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="messages.length === 0 && !isGenerating" class="empty-messages">
            <div class="empty-content">
              <AndroidOutlined class="empty-icon" />
              <p>开始与 AI 对话，完善你的应用</p>
            </div>
          </div>
        </div>

        <!-- 选中元素信息显示 -->
        <div v-if="visualEditorState.selectedElement" class="selected-element-alert">
          <a-alert
            :message="已选中元素: "
            type="info"
            show-icon
            closable
            @close="clearSelectedElement"
          >
            <template #description>
              <div class="element-info">
                <div class="element-details">
                  <span class="element-text">{{ visualEditorState.selectedElement.textContent || '无文本内容' }}</span>
                </div>
                <div class="element-position">
                  位置: ({{ visualEditorState.selectedElement.position.x }}, {{ visualEditorState.selectedElement.position.y }})
                  大小: {{ visualEditorState.selectedElement.position.width }}{{ visualEditorState.selectedElement.position.height }}
                </div>
              </div>
            </template>
          </a-alert>
        </div>

        <!-- 输入区域 -->
        <div class="input-section">
          <div class="input-container">
            <a-textarea
              v-model:value="currentMessage"
              placeholder="描述你想要的功能改进..."
              :rows="3"
              :maxlength="1000"
              :auto-size="{ minRows: 3, maxRows: 6 }"
              class="message-input"
              @keydown="handleKeyDown"
              :disabled="isGenerating"
            />
            <div class="input-actions">
              <div class="char-count">{{ currentMessage.length }}/1000</div>
              <a-space>
                <!-- 编辑模式切换按钮 -->
                <a-button
                  :type="visualEditorState.isEditMode ? 'primary' : 'default'"
                  @click="toggleEditMode"
                  :disabled="isGenerating"
                  class="edit-btn"
                >
                  <template #icon>
                    <EditOutlined />
                  </template>
                  {{ visualEditorState.isEditMode ? '退出编辑' : '编辑' }}
                </a-button>
                <a-button
                  type="primary"
                  @click="() => sendMessage()"
                  :loading="isGenerating"
                  :disabled="!currentMessage.trim() || isGenerating"
                  class="send-btn"
                >
                  <template #icon>
                    <SendOutlined />
                  </template>
                  发送
                </a-button>
              </a-space>
            </div>
          </div>
        </div>
      </div>

      <!-- 分割条 -->
      <div class="splitter" @mousedown="startDrag" :class="{ dragging: isDragging }"></div>

      <!-- 右侧预览区域 -->
      <div class="preview-section" :style="{ width: ${rightWidth}% }">
        <div class="preview-header">
          <h3>网页预览</h3>
          <div class="preview-actions">
            <a-button
              type="text"
              @click="refreshPreview"
              :loading="isRefreshing"
              class="refresh-btn"
            >
              <template #icon>
                <ReloadOutlined />
              </template>
            </a-button>
            <a-button type="text" @click="openInNewTab" class="external-btn">
              <template #icon>
                <LinkOutlined />
              </template>
            </a-button>
          </div>
        </div>
        <div class="preview-content">
          <div v-if="!previewUrl" class="preview-placeholder">
            <div class="placeholder-content">
              <CodeOutlined class="placeholder-icon" />
              <p>应用生成完成后将在此处显示预览</p>
              <p class="placeholder-hint">与AI对话完善你的应用功能</p>
            </div>
          </div>
          <iframe
            v-else
            :src="previewUrl"
            class="preview-iframe"
            frameborder="0"
            @load="handleIframeLoad"
            ref="previewIframe"
          ></iframe>
          <!-- 拖拽时的遮罩层，防止iframe捕获鼠标事件 -->
          <div v-if="isDragging" class="drag-overlay"></div>
          <div v-if="isGenerating" class="generating-overlay">
            <a-spin size="large" />
            <p>AI 正在生成代码中...</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
